import { verify } from '../utils/jwt';
import { endsWith, includes, trimEnd } from 'lodash-es';
import { Context, Next } from 'koa';
import UserService from '../service/UserService';

const pre = '/api/v1';
// 免登录白名单
const whiteList = [pre + '/login', pre + '/test', pre];
const AuthMiddleware = async (ctx: Context, next: Next) => {
  const token = ctx.header['authorization'] as string;
  let path = ctx.path;
  if (endsWith(ctx.path, '/')) {
    path = trimEnd(path, '/');
  }
  //白名单
  if (includes(whiteList, path)) {
    return await next();
  }
  if (token != '' && token != undefined) {
    const { error, admin } = verify(token);
    if (error != null && error != '') {
      throw new global.errs.AuthFailed('认证失败', 401);
      return;
    }
    if (admin != null) {
      global.userinfo = await UserService.getCacheUser(admin['userId']);
      ctx.request['uid'] = admin['userId'];
    }
    return await next();
  } else {
    throw new global.errs.AuthFailed('authorization 为空', 401);
    return;
  }
};
export default AuthMiddleware;
